package com.dzpk.gameserver.util;

import com.dzpk.gameserver.action.CommandEnum;
import com.dzpk.gameserver.protocol.MessageStruct;
import org.apache.mina.core.buffer.IoBuffer;
import somnus.net.message.codec.MessageCodecFactory;

public class CommonPackageUtil {

    public static IoBuffer getDataPackage(int messageId, byte[] data) {
        int packageSize = data.length + GameServerConstants.LENGTH_OF_ACTION_ID + GameServerConstants.LENGTH_OF_ENCRYPT
                + GameServerConstants.TOTAL_MESSAGE_LENGTH;
        IoBuffer buf = IoBuffer.allocate(packageSize, false);

        int dataSize = packageSize - GameServerConstants.TOTAL_MESSAGE_LENGTH;
        buf.putInt(dataSize);
        buf.putInt(messageId);
        // buf.putInt(0);
        // buf.put(data);
        buf.putInt(1);
            buf.put(MessageCodecFactory.encrypt(MessageCodecFactory.SESSION_ENCRYPT, data));
        buf.flip();

        return buf;
    }

    public static IoBuffer getDataPackage(CommandEnum command, byte[] data) {
        return getDataPackage(command.getId(), data);
    }

    public static IoBuffer getDataPackage(CommandEnum command) {
        return getDataPackage(command.getId(), new byte[0]);
    }

    public static IoBuffer getErrorDataPackage(int errorCode) {
        MessageStruct.S2CErrorCode.Builder error = MessageStruct.S2CErrorCode.newBuilder();
        error.setErrorCode(errorCode);
        IoBuffer buf = getDataPackage(CommandEnum.S2C_ERR_CODE.getId(), error.build().toByteArray());
        return buf;
    }

}
